import axios from "axios";  
import { ElMessage } from "element-plus";  

const request = axios.create({  
    baseURL: '', 
    timeout: 30000  
});  

request.interceptors.request.use(config => {  
    config.headers['Content-Type'] = 'application/json;charset=utf-8';  
    return config;  
}, error => {  
    return Promise.reject(error);  
});  

request.interceptors.response.use(  
    response => {  
        let res = response.data;  
        if (typeof res === 'string') {  
            try {  
                res = res ? JSON.parse(res) : res;  
            } catch (e) {  
                console.error('JSON parse error:', e);  
                ElMessage.error('响应数据格式错误');  
                return Promise.reject(e);  
            }  
        }  
        return res;  
    },  
    error => {  
        if (error.response) {  
            if (error.response.status === 404) {  
                ElMessage.error('未找到接口');  
            } else if (error.response.status === 500) {  
                ElMessage.error('系统异常，请查看后端控制台报错');  
            } else {  
                ElMessage.error(`请求失败: ${error.response.status}`);  
            }  
        } else {  
            console.error(error.message);  
        }  
        return Promise.reject(error);  
    }  
);  

request.interceptors.request.use(config => {  
    if (config.push === '/') { 
       } else { 
                 if (sessionStorage.getItem('token')) { 
                         //在请求头加入token，名字要和后端接收请求头的token名字一样    
                         config.headers.token=sessionStorage.getItem('token');        
                  }   
          }  
           return config;  
     },  
     error => { 
        return Promise.reject(error);
     });
  
  //=============================
  //响应回来token是否过期
  request.interceptors.response.use(response => {  
        console.log('响应回来：'+response)  
          //和后端token失效返回码约定403    
          if (response.status === 401) {
                  // 引用elementui message提示框       
                  ElementUI.Message({        
                      message: '身份已失效',  
                      type: 'err'        
                      });
                  //清除token  
                  sessionStorage.removeItem('token');
                  //跳转
                  router.push({name: 'Login'});    
              } else { 
                      return response  
              }  
         }, 
    error => { 
       return Promise.reject(error);  
       })

export default request;